package com.df.tv.launcher.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.df.tv.launcher.R;
import com.df.tv.launcher.activity.MainActivity;
import com.df.tv.launcher.activity.MainActivity.OnHomePressedListener;
import com.df.tv.launcher.entity.HomeNavigationData;
import com.df.tv.launcher.view.DialogGenerator;
import com.df.tv.launcher.view.HomeNavigationView;
import com.df.tv.launcher.view.HomeNavigationView.OnItemClickedListener;
import com.df.tv.launcher.view.HomeNetworkingStatusView;
import com.telecom.tv189.comlib.models.ClickLogSender;
import com.telecom.tv189.comlib.util.Log;

/**
 * 主框架
 */
@SuppressLint("HandlerLeak")
public class MainFrameFragment extends Fragment {
    private static final String TAG = "MainFrameFragment";
    private Fragment homeFragment;
    private Fragment appFragment;
    private SettingFragment settingFragment;

    private static final int USB_STATE_ON = 0x01;
    private static final int USB_STATE_OFF = 0x02;
    private Context mContext;
    private static final int GLOBAL_USB_STATE_ON = 0;
    private static final int GLOBAL_USB_STATE_OFF = 1;
    private boolean isSettingFragmentCreated = false;
    public static boolean isUsbConnecting = false; //USB是否已经挂载,true-已挂载,false-未挂载,进入设置页面是否加载USB数据的标志
    private DialogGenerator mDialogDenerator;
    private USBDetectBroadcastReceiver mUSBReceiver = new USBDetectBroadcastReceiver();

    private Handler mMainHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case GLOBAL_USB_STATE_ON://检测到USB连接,弹出Dialog对话框
                mDialogDenerator.createUsbDetectedDialog();
                break;
            case GLOBAL_USB_STATE_OFF:
                if (mDialogDenerator.isShowing()) {
                    mDialogDenerator.dismiss();
                }
            default:
                break;
            }
        };
    };
    private HomeNetworkingStatusView netWorking;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        homeFragment = new HomeViewPagerFragment();
        appFragment = new ApplicationFragment();
        settingFragment = new SettingFragment();
        this.registerReceiver();//注册USB监听事件
        mDialogDenerator = new DialogGenerator(mContext);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 得到我首页整体布局
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.home_ensemble_activity, container, false);
        netWorking = (HomeNetworkingStatusView) root.findViewById(R.id.netWorking);

        // 得到导航区的View
        HomeNavigationView navigationView = (HomeNavigationView) root.findViewById(R.id.navigationView);

        navigationView.setOnItemClickListener(new OnItemClickedListener() {
            @Override
            public void onClick(View v, int id) {
                HomeNavigationData data = (HomeNavigationData) v.getTag();
                if (data == null)
                    return;
                String type = data.getType();
                if (type.equals("sy")) {
                    // 跳转首页 fragment
                    settingFragment(homeFragment);
                }
                else if (type.equals("yy")) {
                    // 跳转应用 fragment
                    settingFragment(appFragment);
                }
                else if (type.equals("sz")) {
                    // 跳转设置fragment
                    settingFragment(settingFragment);
                }
                else {
                    if (TextUtils.isEmpty(data.getApppkg()))
                        return;
                    // 通过包名
                    PackageManager pkManager = getActivity().getPackageManager();
                    Intent intent = pkManager.getLaunchIntentForPackage(data.getApppkg());
                    try {
                        Context context = getActivity().getApplicationContext();
                        context.startActivity(intent);
                    } catch (NullPointerException exception) {
                        Toast.makeText(getActivity(), R.string.navigation_exception, 1).show();
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(getActivity(), R.string.navigation_exception, 1).show();
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), R.string.navigation_exception, 1).show();
                    }
                    try {
                        ClickLogSender.getInstance(getActivity()).sendLog(v, data.getLogtag());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).setOnHomePressedListener(new OnHomePressedListener() {

                @Override
                public boolean onHomePressed() {
                    try {
                        settingFragment(homeFragment);
                    } catch (IllegalStateException e) {
                        //java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
                        Log.e(TAG, e.getMessage());
                        return false;
                    }
                    return true;
                }
            });
        }
        // 首页 第一个fragment
        getChildFragmentManager().beginTransaction().replace(R.id.fl, homeFragment).commit();
        return root;
    }

    // 跳转 fragment
    private void settingFragment(Fragment fragment) {
        FragmentTransaction beginTransaction = getChildFragmentManager().beginTransaction();
        // 给fragment添加一个切换动画
        beginTransaction.setCustomAnimations(R.anim.home_push_in, R.anim.home_push_out);
        beginTransaction.replace(R.id.fl, fragment).commit();
        //isSettingFragmentCreated = true;
        if (fragment == settingFragment) {
            isSettingFragmentCreated = true;//用于SettingsFragment界面上的Handler发送消息,处理GridView的显示
        }
        else {
            isSettingFragmentCreated = false;
        }
    }

    /**
     * 注册服务,监听USB
     */
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter.addAction(Intent.ACTION_MEDIA_SHARED);
        filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);

        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addDataScheme("file");
        mContext.registerReceiver(mUSBReceiver, filter);
    }

    private void unRegisterReceiver() {
        mContext.unregisterReceiver(mUSBReceiver);
    }

    private class USBDetectBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, intent.getAction());
            if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)
                    || intent.getAction().equals(Intent.ACTION_MEDIA_CHECKING)) {//挂载USB
                isUsbConnecting = true;//是否挂载USB标志位,当前已挂载
                if (isSettingFragmentCreated) {
                    settingFragment.mHandler.sendEmptyMessage(USB_STATE_ON);//当前界面是设置界面
                }
                else {
                    mMainHandler.sendEmptyMessage(GLOBAL_USB_STATE_ON);//当前界面是其他界面
                }
            }
            else if (intent.getAction().equals(Intent.ACTION_MEDIA_BAD_REMOVAL)) {//卸载USB
                isUsbConnecting = false;//是否挂载USB标志位,当前未挂载
                if (isSettingFragmentCreated) {
                    settingFragment.mHandler.sendEmptyMessage(USB_STATE_OFF);
                }
                else {
                    mMainHandler.sendEmptyMessage(GLOBAL_USB_STATE_OFF);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        netWorking.NetWorkingRegisterReceiver(getActivity());
    }

    @Override
    public void onPause() {
        super.onPause();
        netWorking.NetWorkingUnregisterReceiver(getActivity());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isSettingFragmentCreated = false;
        isUsbConnecting = false;
        unRegisterReceiver();
        if (mDialogDenerator != null && mDialogDenerator.isShowing()) {
            mDialogDenerator.dismiss();
            mDialogDenerator = null;
        }
    }
}
